package com.cdu.guoxinan.www.smartcom.controller;

import com.cdu.guoxinan.www.smartcom.aop.Annotation.OperationLog;
import com.cdu.guoxinan.www.smartcom.domian.dto.ProductQueryDTO;
import com.cdu.guoxinan.www.smartcom.domian.pojo.Product;
import com.cdu.guoxinan.www.smartcom.service.ProductService;
import com.cdu.guoxinan.www.smartcom.unit.model.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.github.pagehelper.PageInfo;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    @GetMapping("/list")
    public R listProducts(@RequestParam(required = false) String category,
                          @RequestParam(required = false) String keyword) {
        List<Product> products;
        if ((category == null || category.isEmpty()) && (keyword == null || keyword.isEmpty())) {
            products = productService.getAllProducts();
        } else {
            products = productService.getProductsByCategoryAndName(category, keyword);
        }
        return R.ok(products, products.size());
    }

    @GetMapping("/page")
    public R queryPage(ProductQueryDTO productQueryDTO) {
        PageInfo<Product> pageInfo = productService.queryPage(productQueryDTO);
        return R.ok(pageInfo.getList(), pageInfo.getTotal());
    }
    
    @PostMapping("/add")
    @OperationLog(description = "添加商品")//日志注解
    public R addProduct(Product product) {
        try {
            productService.addProduct(product);
            return R.ok();
        } catch (Exception e) {
            return R.error("添加商品失败: " + e.getMessage());
        }
    }

    @PostMapping("/update")
    public R updateProduct(Product product, @RequestParam(required = false) Long originalId) {
        try {
            // 如果提供了原始ID，使用原始ID进行更新
            if (originalId != null) {
                product.setProductId(originalId);
            }
            
            productService.updateProduct(product);
            return R.ok();
        } catch (Exception e) {
            return R.error("更新商品失败: " + e.getMessage());
        }
    }

    @GetMapping("/delete/{productId}")
    public R deleteProduct(@PathVariable Long productId) {
        try {
            productService.deleteProduct(productId);
            return R.ok();
        } catch (Exception e) {
            return R.error("删除商品失败: " + e.getMessage());
        }
    }
} 